<?php

require __DIR__ . '/../../vendor/autoload.php';

$webSocket = new Swoole\WebSocket\Server('0.0.0.0', 9501);

$webSocket->on('Open', function (\Swoole\WebSocket\Server $webSocket, \Swoole\Http\Request $request) {
    $webSocket->push($request->fd, "hello, welcome\n");
});

$webSocket->on('Message', function (\Swoole\WebSocket\Server $webSocket, \Swoole\WebSocket\Frame $frame) {
    echo "Message: {$frame->data}\n";
    $webSocket->push($frame->fd, "server: {$frame->data}");
});

$webSocket->on('Request', function (Swoole\Http\Request $request, Swoole\Http\Response $response) {
    global $webSocket;

    foreach ($webSocket->connections as $fd) {
        if ($webSocket->isEstablished($fd)) {
            $webSocket->push($fd, $request->get['message']);
        }
    }

    $response->end('hello!');
});

$webSocket->on('Close', function (\Swoole\WebSocket\Server $webSocket, $fd) {
    echo "client-{$fd} is closed\n";
});

$webSocket->start();
